import { Login, getUserInfo } from "@/api/sys";
import { TOKEN } from "../../contants";
import {
  getItem,
  setItem,
  removeAllItem,
  removeItem,
} from "../../Util/storage";
import router from "../../router";

// import md5 from "md5";
export default {
  namespaced: true,
  state: () => ({
    token: getItem(TOKEN) || "",
    userinfo: {}, //更详细的用户信息
  }),
  // 同步  突变器
  mutations: {
    setToken(state, token) {
      setItem(TOKEN, token);
      state.token = token;
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
  },
  // 异步
  actions: {
    Login(context, userInfo) {
      console.log("userinfo", userInfo);
      const { username, password } = userInfo;
      // 收到new Promise的包裹
      return new Promise((resolve, reject) => {
        Login({
          mobile: username,
          password: password,
        })
          .then((res) => {
            this.commit("user/setToken", res.data._token);
            resolve(res); //  把结果传送回原来的调用地方
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 登录写法2
    // async Login(context, userInfo) {
    //   const { username, password } = userInfo;
    //   const res = await Login({
    //     mobile: username,
    //     password: password,
    //   });
    //   this.commit("user/setToken", res.data._token);
    //   return res;
    // },

    async getUserInfo() {
      const res = await getUserInfo();
      console.log("更多详细信息");
      console.log(res);
      let userRights = JSON.stringify(res.rights);
      window.sessionStorage.setItem("userRights", userRights); // 权限seesion
      this.commit("user/setUserInfo", res);
    },

    // logout action 主动退出
    logout() {
      this.commit("user/setToken", "");
      // this.commit("user/setUserInfo", {});
      removeAllItem();
      window.sessionStorage.clear();
      router.push("/login");
    },
  },
};
